const path = require('path')
const fg = require('fast-glob')
const execa = require('execa')
const minimist = require('minimist')
const commit = execa.sync('git', ['rev-parse', 'HEAD']).stdout
const args = minimist(process.argv.slice(2))
const sourceMap = args.sourcemap || args.s
const env = args.env || args.e

const pkgFiles = fg.sync(['packages/**/package.json'], { dot: true })

pkgFiles.forEach(pkgPath => {
  const target = pkgPath.split('/')[1]
  const pkg = require(path.resolve(pkgPath))
  const {
    buildOptions: { name, formats }
  } = pkg
  execa(
    'rollup',
    [
      '-c',
      // "--bundleConfigAsCjs",
      '--environment',
      [
        `COMMIT:${commit}`,
        `NODE_ENV:${env}`,
        `TARGET:${target}`,
        `FORMATS:${formats}`,
        `SOURCE_MAP:${sourceMap}`
      ]
    ],
    {
      stdio: 'inherit'
    }
  )
})
